package com.sms.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sms.dao.IBatchSmsDAO;
import com.sms.po.TTask;

public class BatchSmsDAO extends HibernateDaoSupport implements IBatchSmsDAO {
	private static final Log log = LogFactory.getLog(BatchSmsDAO.class);
	@Override
	public boolean addBatchSms(TTask ca) {
		log.info("add a batchSms instance");
		try {
			this.getHibernateTemplate().save(ca);
			return true;
		} catch (Exception e) {
			log.error("add a batchSms instance fial!!",e);
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TTask> findBatchSmsByPage(final Map<Object, Object> map) {
		log.info("find batchSms instances");
		try{
			return (List<TTask>) this.getHibernateTemplate().execute(new HibernateCallback(){

				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					StringBuffer hql = new StringBuffer("from TTask where 1=1 ");
					String userType=map.get("userType").toString();//1-系统用户，2-代理用户，3-普通用户
					if("2".equals(userType)){
						hql.append(" and (userId=:userId or parentId=:parentId)");
					}else if("3".equals(userType)){
						hql.append(" and userId=:userId");
					}
					
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0 &&
							map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') between :beginDate and :endDate ");
					}else if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') >= :beginDate");
					}else if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') <= :endDate");
					}else{
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') = DATE_FORMAT(CURRENT_DATE,'%Y%m%d')");
					}
					if(map.get("content") != null && map.get("content").toString().trim().length() > 0){
						hql.append(" and content like :content");
					}
					if(map.get("taskName") != null && map.get("taskName").toString().trim().length() > 0){
						hql.append(" and taskName like :taskName");
					}
					
					Query q = session.createQuery(hql.toString());
					if("2".equals(userType)){
						q.setString("userId", map.get("userId").toString());
						q.setString("parentId", map.get("parentId").toString());
					}else if("3".equals(userType)){
						q.setString("userId", map.get("userId").toString());
					}
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						q.setInteger("beginDate", Integer.valueOf(map.get("beginDate").toString()));
					}
					if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						q.setInteger("endDate", Integer.valueOf(map.get("endDate").toString()));
					}
					if(map.get("content") != null && map.get("content").toString().trim().length() > 0){
						q.setString("content", "%"+map.get("content").toString()+"%");
					}
					if(map.get("taskName") != null && map.get("taskName").toString().trim().length() > 0){
						q.setString("taskName", "%"+map.get("taskName").toString()+"%");
					}
					
					//split page
					
					if(map.get("start") != null && map.get("start").toString().trim().length() > 0){
						q.setFirstResult(Integer.valueOf(map.get("start").toString()));
					}
					if(map.get("limit") != null && map.get("limit").toString().trim().length() > 0){
						q.setMaxResults(Integer.valueOf(map.get("limit").toString()));
					}
					
					List<TTask> l =  q.list();
					return l == null ? new ArrayList<TTask>() : l;
				}});
			
		}catch(Exception e){
			log.error("find batchSms instance", e);
			return null;
		}finally{
//			session.close();
		}
	}

	@Override
	public int findBatchSmsByPageCount(final Map<Object, Object> map) {
		log.info("find batchSms instances count");
		try{
			return Integer.valueOf(this.getHibernateTemplate().execute(new HibernateCallback(){
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					StringBuffer hql = new StringBuffer("select count(*) from TTask where 1=1 ");
					String userType=map.get("userType").toString();//1-系统用户，2-代理用户，3-普通用户
					if("2".equals(userType)){
						hql.append(" and (userId=:userId or parentId=:parentId)");
					}else if("3".equals(userType)){
						hql.append(" and userId=:userId");
					}
					
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0 &&
							map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') between :beginDate and :endDate ");
					}else if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') >= :beginDate");
					}else if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') <= :endDate");
					}else{
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') = DATE_FORMAT(CURRENT_DATE,'%Y%m%d')");
					}
					if(map.get("content") != null && map.get("content").toString().trim().length() > 0){
						hql.append(" and content like :content");
					}
					if(map.get("taskName") != null && map.get("taskName").toString().trim().length() > 0){
						hql.append(" and taskName like :taskName");
					}
					
					Query q = session.createQuery(hql.toString());
					if("2".equals(userType)){
						q.setString("userId", map.get("userId").toString());
						q.setString("parentId", map.get("parentId").toString());
					}else if("3".equals(userType)){
						q.setString("userId", map.get("userId").toString());
					}
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						q.setInteger("beginDate", Integer.valueOf(map.get("beginDate").toString()));
					}
					if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						q.setInteger("endDate", Integer.valueOf(map.get("endDate").toString()));
					}
					if(map.get("content") != null && map.get("content").toString().trim().length() > 0){
						q.setString("content", "%"+map.get("content").toString()+"%");
					}
					if(map.get("taskName") != null && map.get("taskName").toString().trim().length() > 0){
						q.setString("taskName", "%"+map.get("taskName").toString()+"%");
					}
					return q.list().get(0).toString();
				}}).toString() ).intValue();
			
		}catch(Exception e){
			log.error("find batchSms instance count", e);
			return 0;
		}
	}

	@Override
	public boolean removeBatchSms(TTask ca) {
		log.info("remove a batchSms instance");
		try {
			this.getHibernateTemplate().delete(ca);
			return true;
		} catch (Exception e) {
			log.error("add a batchSms instance fial!!",e);
			return false;
		}
	}

	@Override
	public boolean updateBatchSms(TTask ca) {
		log.info("update a batchSms instance");
		try {
			this.getHibernateTemplate().update(ca);
			return true;
		} catch (Exception e) {
			log.error("update a batchSms instance fial!!",e);
			return false;
		}
	}

}
